package com.magicodex.bookkeeping.biz.common.util;

import com.magicodex.bookkeeping.biz.common.constant.NumberConstants;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * @author mh.z
 */
public class NumberUtil {

    /**
     * 解析成数字
     *
     * @param text
     * @return
     */
    public static BigDecimal parseNumber(String text) {
        if (StringUtil.isEmpty(text)) {
            return null;
        }

        return new BigDecimal(text);
    }

    /**
     * 解析成数字
     *
     * @param text
     * @param scale
     * @return
     */
    public static BigDecimal parseNumber(String text, int scale) {
        if (StringUtil.isEmpty(text)) {
            return null;
        }

        BigDecimal number = new BigDecimal(text);
        number = number.setScale(scale, RoundingMode.DOWN);

        return number;
    }

    /**
     * 解析成数字
     *
     * @param text
     * @return
     */
    public static BigDecimal parseNumberWithDefaultFmt(String text) {
        return parseNumber(text, NumberConstants.NUMBER_2);
    }

    /**
     * 格式化成字符串
     *
     * @param number
     * @return
     */
    public static String formatNumber(BigDecimal number) {
        if (number == null) {
            return null;
        }

        return number.toString();
    }

    /**
     * 格式化成字符串
     *
     * @param number
     * @param scale
     * @return
     */
    public static String formatNumber(BigDecimal number, int scale) {
        if (number == null) {
            return null;
        }

        number = number.setScale(scale, RoundingMode.DOWN);

        return number.toString();
    }

    /**
     * 格式化成字符串
     *
     * @param number
     * @return
     */
    public static String formatNumberWithDefaultFmt(BigDecimal number) {
        return formatNumber(number, NumberConstants.NUMBER_2);
    }

    /**
     * 格式化成字符串
     *
     * @param number
     * @return
     */
    public static String formatNumberWithThousandsFmt(BigDecimal number) {
        if (number == null) {
            return null;
        }

        number = number.setScale(NumberConstants.NUMBER_2, RoundingMode.DOWN);
        DecimalFormat format = new DecimalFormat("#,##0.00");

        return format.format(number);
    }

}
